package com.yanchi.controller;

import com.yanchi.service.UserService;
import com.yanchi.entity.User;
import com.yanchi.util.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("user")
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * 用来注册用户
     * @return
     */
    @PostMapping("register")
    public String register(User user){

        String password = user.getPassword();
        String slot = ShiroUtil.getSlot(8);

        Md5Hash md5Hash = new Md5Hash(password,slot,1024);

        user.setPassword(md5Hash.toHex());
        user.setSlot(slot);

        try {
            userService.addUser(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("注册失败！");
            return "redirect:/register.jsp";
        }
    }


    /**
     * 用来退出登录
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/login.jsp";
    }

    /**
     * 用来处理身份认证
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("login")
    public String login(String username, String password){

        Subject subject = SecurityUtils.getSubject();

        try{
            subject.login(new UsernamePasswordToken(username,password));   // 用户认证
            return "redirect:/main.jsp";
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println(" 认证失败：用户不存在！");
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println(" 认证失败：密码错误！");
        } catch (Exception e){
            e.printStackTrace();
        }

        return "redirect:/login.jsp";
    }


}
